<?php

namespace ff\caching;

class Redis
{
    public static $config = array();
    public static $link = array();
    public static $default = '';

    public function __construct($config)
    {
        self::$config = $config;
        self::$default = $config['default'];
    }

    public static function connect($confkey = '')
    {

        $confkey = $confkey ? $confkey : self::$default;

        if (empty(self::$link[$confkey])) {

            $config = self::$config[$confkey];

            if (!empty($config['server'])) {
                self::$default = $confkey;

                $prefix = $config['prefix'];
                try {
                    self::$link[$confkey] = new Redis();
                    if (self::$config['pconnect']) {
                        $connect = @self::$link[$confkey]->pconnect($config['server'], $config['port'], $config['connect_timeout']);
                    } else {
                        $connect = @self::$link[$confkey]->connect($config['server'], $config['port'], $config['connect_timeout']);
                    }
                } catch (RedisException $e) {

                }
                if ($connect) {
                    if ($config['password']) {
                        @self::$link[$confkey]->auth($config['password']);
                    }
                    if ($config['prefix']) {
                        self::$link[$confkey]->setOption(Redis::OPT_PREFIX, $config['prefix']);
                    }
                    self::$link[$confkey]->select($config['db']);
                }
            }
        }
        return self::$link[$confkey];
    }

}
